import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { getToken, removeToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 10000, // 请求超时时间
  withCredentials: false
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.params = removeNull(config.params)
    return config
  },
  error => {
    // Do something with request error
    console.log('request error') // for debug
    Message({
      message: '请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    Promise.reject(error)
  }
)

// response拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log('response error') // for debug
    if (error && error.response && error.response.data) {
      const errorData = error.response.data
      /* token超时直接退出到登录页面 */
      if (errorData.errorCode && errorData.errorCode === 1104) {
        removeToken()
        location.reload()
        return
      }
      if (errorData.errorDesc) {
        error.message = errorData.errorDesc
      } else {
        error.message = '未知错误'
      }
    } else {
      error.message = '连接服务器失败!'
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

function removeNull(obj) {
  if (!(typeof obj === 'object')) {
    return
  }
  for (var key in obj) {
    if (obj.hasOwnProperty(key) && (obj[key] === null || obj[key] === undefined || obj[key] === '')) { delete obj[key] }
  }
  return obj
}
export default service
